package cn.ydt.ydt.shopping.webapi.service.impl;

import cn.ydt.ydt.common.exception.YdtServiceException;
import cn.ydt.ydt.common.resful.StatusCode;
import cn.ydt.ydt.common.utils.FileNameUtils;
import cn.ydt.ydt.pojo.shopping.dto.AddVegetableDTO;
import cn.ydt.ydt.pojo.shopping.dto.CreateVegetableOrderDTO;
import cn.ydt.ydt.pojo.shopping.dto.GetSimpleCartDTO;
import cn.ydt.ydt.pojo.shopping.dto.SimpleVegetableDTO;
import cn.ydt.ydt.pojo.shopping.model.Vegetable;
import cn.ydt.ydt.pojo.shopping.model.VegetableCart;
import cn.ydt.ydt.pojo.shopping.model.VegetableOrder;
import cn.ydt.ydt.pojo.shopping.model.VegetableOrderCart;
import cn.ydt.ydt.pojo.shopping.vo.*;
import cn.ydt.ydt.pojo.user.vo.UserShowInfoVO;
import cn.ydt.ydt.pojo.work.dto.WorkDTO;
import cn.ydt.ydt.shopping.service.IVegetableService;
import cn.ydt.ydt.shopping.webapi.mapper.IVegetableMapper;
import cn.ydt.ydt.shopping.webapi.utils.SecurityContextUtils;
import cn.ydt.ydt.user.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import service.IWorkService;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;


@Service
@Slf4j
public class VegetableServiceImpl implements IVegetableService {

    @Autowired
    IVegetableMapper vegetableMapper;

    @DubboReference
    IWorkService workService;

    @DubboReference
    IUserService userService;


    @Override
    public void addVegetable(AddVegetableDTO addVegetableDTO) {
        log.info("申明一个vegetable并把传递过来的参数复制到其中");
        Vegetable addVegetable = new Vegetable();
        BeanUtils.copyProperties(addVegetableDTO,addVegetable);
        log.info("复制完成，补全信息");
        LocalDateTime localDateTime = LocalDateTime.now();
        addVegetable.setCreateTime(localDateTime);
        addVegetable.setModifyTime(localDateTime);
        Long NetCommunityId = SecurityContextUtils.getNetCommunityId();
        addVegetable.setCommunityId(NetCommunityId);
        addVegetable.setIsDeleted((byte)0);
        log.info("信息补全完成，添加到数据库");
        vegetableMapper.addVegetable(addVegetable);

    }

    @Override
    public List<SimpleVegetableVO> getVegetableService(String vegetableSort) {
        log.info("判断传过来的参数是否为空");
        if (vegetableSort == null){
            log.info("参数为空,抛出异常");
            throw new YdtServiceException(StatusCode.BAD_REQUEST,"传递过来的类别参数为空");
        }
        log.info("查询对应类别的菜品");
        List<SimpleVegetableVO> list = vegetableMapper.getVegetableBySort(vegetableSort);

        log.info("拼接文件名");
        for (SimpleVegetableVO vegetableVO : list){
            vegetableVO.setVegetableImage(FileNameUtils.filePath(vegetableVO.getVegetableImage()));
        }
        log.info("list={}"+list.toString());
        return list;
    }

    @Override
    public void addVegetableCart(SimpleVegetableDTO simpleVegetableDTO) {
        log.info("判断传过来的数据是否为空");
        if (simpleVegetableDTO == null){
            log.warn("数据为空,抛出异常");
            throw new YdtServiceException(StatusCode.BAD_REQUEST,"传过来的订单数据为空");
        }
        log.info("创建一个VegetableCart对象,把传过来对应的数据添加到这个对象中");
        Long userId = SecurityContextUtils.getUserId();
        String vegetableName = simpleVegetableDTO.getVegetableName();
        Vegetable vegetable1 = vegetableMapper.getVegetableByName(vegetableName);
        if (vegetable1 == null){
            throw new YdtServiceException(StatusCode.BAD_REQUEST,"该菜品不存在");
        }
        Long vegetableId1 = vegetable1.getVegetableId();
        GetSimpleCartDTO getSimpleCartDTO = new GetSimpleCartDTO();
        getSimpleCartDTO.setUserId(userId);
        getSimpleCartDTO.setVegetableId(vegetableId1);
        VegetableCart testVegetableCart = vegetableMapper.getCartByUserIdAndVegetableId(getSimpleCartDTO);
        if (testVegetableCart !=null){
            Long VCartId = testVegetableCart.getCartId();
            AddSameCartVO addSameCartVO = new AddSameCartVO();
            addSameCartVO.setCartId(VCartId);
            addSameCartVO.setCartCount(simpleVegetableDTO.getCartCount());
            log.info("购物车存在，添加原来购物车数量{}",addSameCartVO);
            vegetableMapper.addSameCart(addSameCartVO);
            return;
        }

        VegetableCart vegetableCart = new VegetableCart();
        BeanUtils.copyProperties(simpleVegetableDTO,vegetableCart);
        String VegetableName = simpleVegetableDTO.getVegetableName();
        Vegetable vegetable = vegetableMapper.getVegetableByName(VegetableName);
        if (vegetable == null){
            throw new YdtServiceException(StatusCode.BAD_REQUEST,"不存在该菜品");
        }
        Long vegetableId = vegetable.getVegetableId();
        vegetableCart.setUserId(userId);
        vegetableCart.setVegetableId(vegetableId);
        log.info("添加其它的参数");
        LocalDateTime dateTime = LocalDateTime.now();

        vegetableCart.setIsDeleted((byte)0);
        vegetableCart.setCreateTime(dateTime);
        vegetableCart.setModifyTime(dateTime);
        log.info("数据添加完成,把购物车数据插入数据库");
        vegetableMapper.addVegetableCart(vegetableCart);
        log.info("插入成功!");
    }

    @Override
    public void delVegetableCart(Long cartId) {
        log.info("判断cartId是否为空");
        if (cartId == null){
            log.warn("cartId为空抛出异常");
            throw new YdtServiceException(StatusCode.BAD_REQUEST,"购物车id为空");
        }
        log.info("根据cartId获取对应cart信息");
        VegetableCart cart = vegetableMapper.getCartByCartId(cartId);
        if (cart == null){
            log.warn("该cartId对应的购物车不存在，抛出异常");
            throw new YdtServiceException(StatusCode.BAD_REQUEST,"该购物车不存在！");
        }
        log.info("获取其中的isdelete属性判断是否删除");
        Byte isdelete = cart.getIsDeleted();
        log.info("‘判断是否已经被删除");
        if (isdelete == 1){
            log.info("该购物车已经被删除抛出异常");
            throw new YdtServiceException(StatusCode.BAD_REQUEST,"该购物车已经被删除，请刷新页面");
        }
        log.info("调用删除方法");
        vegetableMapper.delVegetableCart(cartId);
    }

    @Override
    public void addVegetableOrder(CreateVegetableOrderDTO orderDTO) {
        List<Long> carts = new ArrayList<>();
        carts = orderDTO.getCarts();
        for (Long item : carts){
            VegetableCart vegetableCart = vegetableMapper.getCartByCartId(item);
            if(vegetableCart == null){
                throw new YdtServiceException(StatusCode.BAD_REQUEST,"该购物车不存在");
            }
        }
        log.info("获取当前登录用户id");
        Long userId = SecurityContextUtils.getUserId();
        log.info("添加订单");
        UserShowInfoVO userShowInfoVO = userService.findUserById(userId);
        String address = userShowInfoVO.getUserAddress();
        log.info("获取用户地址：{}",address);
        LocalDateTime dateTime = LocalDateTime.now();
        VegetableOrder vegetableOrder = new VegetableOrder();
        vegetableOrder.setUserId(userId);
        vegetableOrder.setIsComplete((byte)0);
        vegetableOrder.setOrderAddress(address);
        vegetableOrder.setGmtCreate(dateTime);
        vegetableOrder.setGmtModified(dateTime);
        vegetableMapper.addVegetableOrder(vegetableOrder);

        log.info("开始调用任务模块");
        WorkDTO workDTO = new WorkDTO();
        workDTO.setWorkName("配送菜品任务");
        workDTO.setWorkAddress(address);
        workDTO.setWorkInfo("");
        log.info("遍历购物车id查出菜品信息存入任务表中");
        for (Long carId : carts){
            VegetableCart vegetableCart = vegetableMapper.getCartByCartId(carId);
            if(vegetableCart == null){
                throw new YdtServiceException(StatusCode.BAD_REQUEST,"该购物车不存在");
            }
            log.info("查询出的购物车信息：{}",vegetableCart.toString());
            Long vegetableId = vegetableCart.getVegetableId();
            Vegetable vegetable = vegetableMapper.getVegetableById(vegetableId);
            if (vegetable == null){
                throw new YdtServiceException(StatusCode.BAD_REQUEST,"菜品不存在");
            }
            String workInformation = workDTO.getWorkInfo();
            workDTO.setWorkInfo(workInformation+"菜品名："+vegetable.getVegetableName()+";菜品数量："+vegetableCart.getCartCount()+";");
        }
        workService.addNewWork(workDTO);

        log.info("添加订单完成，添加订单购物车关系,并移除添加到订单中包含的购物车");
        log.info("购物车id列表为：{}",carts);
        for (Long cartId : carts){
            VegetableOrderCart orderCart = new VegetableOrderCart();
            log.info("cartId:{}"+cartId);
            orderCart.setVegetableCartId(cartId);
            orderCart.setVegetableOrderId(vegetableOrder.getVegetableOrderId());
            orderCart.setCreateTime(dateTime);
            orderCart.setModifyTime(dateTime);
            vegetableMapper.addOrderCart(orderCart);
            vegetableMapper.delVegetableCart(cartId);
        }
    }

    @Override
    public void updateOrderComplete(Long orderId) {
        log.info("修改订单为已完成");
        vegetableMapper.updateOrderComplete(orderId);
    }

    @Override
    public List<OrderCartVO> getOrderCartByOrderId() {
        log.info("得到当前的用户id");
        Long userId = SecurityContextUtils.getUserId();
        log.info("根据用户查询订单列表");
        List<VegetableOrder> orderList = vegetableMapper.getOrderByUserId(userId);
        log.info("根据订单id查询购物车");
        List<OrderCartVO> orderCartVO = new ArrayList<>();
        for (VegetableOrder order : orderList){
            Long orderId = order.getVegetableOrderId();
            List<VegetableOrderCart> orderCart = vegetableMapper.getOrderCartByOrderId(orderId);
            List<Long> cartIdList = new ArrayList<>();
            Double allPrice = 0.0;
            for (VegetableOrderCart vegetableOrderCart : orderCart){
                Long cartId = vegetableOrderCart.getVegetableCartId();
                VegetableCart cart = vegetableMapper.getCart(cartId);
                if (cart == null){
                    throw new YdtServiceException(StatusCode.BAD_REQUEST,"该购物车不存在");
                }
                Long vegetableId = cart.getVegetableId();
                Vegetable  vegetable= vegetableMapper.getVegetableById(vegetableId);
                if (vegetable == null){
                    throw new YdtServiceException(StatusCode.BAD_REQUEST,"该菜品不存在");
                }
                Double price = vegetable.getVegetablePrice();
                Integer count = cart.getCartCount();
                Double cartPrice = price*count;
                allPrice = allPrice+cartPrice;
                cartIdList.add(cartId);
            }
            OrderCartVO orderCartItem = new OrderCartVO();
            orderCartItem.setOrderId(orderId);
            orderCartItem.setAllPrice(allPrice);
            orderCartItem.setCartIdList(cartIdList);
            orderCartItem.setAddress(order.getOrderAddress());
            orderCartVO.add(orderCartItem);
        }
        return orderCartVO;
    }

    @Override
    public List<SimpleCartVO> getCartByUserId() {
        Long userId = SecurityContextUtils.getUserId();
        List<SimpleCartVO> simpleCartVOS = new ArrayList<>();
        List<VegetableCart> cartList = vegetableMapper.getCartListByUserId(userId);
        for (VegetableCart cart : cartList){
            SimpleCartVO simpleCartVO = new SimpleCartVO();
            if (cart == null){
                throw new YdtServiceException(StatusCode.BAD_REQUEST,"该购物车不存在");
            }
            Long vegetableId = cart.getVegetableId();
            Vegetable vegetable = vegetableMapper.getVegetableById(vegetableId);
            if (vegetable == null){
                throw new YdtServiceException(StatusCode.BAD_REQUEST,"该菜品不存在");
            }
            BeanUtils.copyProperties(cart,simpleCartVO);
            BeanUtils.copyProperties(vegetable,simpleCartVO);
            String img = simpleCartVO.getVegetableImage();
            simpleCartVO.setVegetableImage(FileNameUtils.filePath(img));
            simpleCartVOS.add(simpleCartVO);
        }
        return simpleCartVOS;
    }

    @Override
    public Vegetable getVegetableById(Long id) {
        if (id==null){
            throw new YdtServiceException(StatusCode.BAD_REQUEST,"菜品id为空");
        }
        Vegetable vegetable = vegetableMapper.getVegetableById(id);
        String img = vegetable.getVegetableImage();
        vegetable.setVegetableImage(FileNameUtils.filePath(img));
        return vegetable;
    }

    @Override
    public Vegetable getVegetableByName(String name) {
        if (name == null){
            throw new YdtServiceException(StatusCode.BAD_REQUEST,"菜品名为空");
        }
        Vegetable vegetable = vegetableMapper.getVegetableByName(name);
        if (vegetable == null){
            throw new YdtServiceException(StatusCode.BAD_REQUEST,"不存在该菜品");
        }
        return vegetable;
    }

    @Override
    public SimpleCartVO getCartById(Long cartId) {
        if (cartId == null){
            throw new YdtServiceException(StatusCode.BAD_REQUEST,"购物车id为空");
        }
        SimpleCartVO simpleCartVO = new SimpleCartVO();
        VegetableCart cart = vegetableMapper.getCart(cartId);
        if (cart == null){
            throw new YdtServiceException(StatusCode.BAD_REQUEST,"该购物车不存在");
        }
        Long VegetableId = cart.getVegetableId();
        Vegetable vegetable = vegetableMapper.getVegetableById(VegetableId);
        if (vegetable == null){
            throw new YdtServiceException(StatusCode.BAD_REQUEST,"该菜品不存在");
        }
        BeanUtils.copyProperties(cart,simpleCartVO);
        BeanUtils.copyProperties(vegetable,simpleCartVO);
        String img = simpleCartVO.getVegetableImage();
        simpleCartVO.setVegetableImage(FileNameUtils.filePath(img));
        return simpleCartVO;
    }

    @Override
    public List<DetailOrderCartVO> getOrderCart() {
        log.info("根据用户查询订单列表");
        List<VegetableOrder> orderList = vegetableMapper.getOrder();
        log.info("根据订单id查询购物车");
        List<OrderCartVO> orderCartVO = new ArrayList<>();
        List<DetailOrderCartVO> detailOrderCartVOS = new ArrayList<>();
        for (VegetableOrder order : orderList){
            Long userId = order.getUserId();
            Long orderId = order.getVegetableOrderId();
            List<VegetableOrderCart> orderCart = vegetableMapper.getOrderCartByOrderId(orderId);
            List<Long> cartIdList = new ArrayList<>();
            Double allPrice = 0.0;
            for (VegetableOrderCart vegetableOrderCart : orderCart){
                Long cartId = vegetableOrderCart.getVegetableCartId();
                VegetableCart cart = vegetableMapper.getCart(cartId);
                if (cart == null){
                    throw new YdtServiceException(StatusCode.BAD_REQUEST,"该购物车不存在");
                }
                Long vegetableId = cart.getVegetableId();
                Vegetable  vegetable= vegetableMapper.getVegetableById(vegetableId);
                if (vegetable == null){
                    throw new YdtServiceException(StatusCode.BAD_REQUEST,"该菜品不存在");
                }
                Double price = vegetable.getVegetablePrice();
                Integer count = cart.getCartCount();
                Double cartPrice = price*count;
                allPrice = allPrice+cartPrice;
                cartIdList.add(cartId);
            }
            OrderCartVO orderCartItem = new OrderCartVO();
            orderCartItem.setOrderId(orderId);
            orderCartItem.setAllPrice(allPrice);
            List<SimpleCartVO> simpleCartVOS = new ArrayList<>();
            for (Long cId : cartIdList){
                SimpleCartVO simpleCartVO = getCartById(cId);
                simpleCartVOS.add(simpleCartVO);
            }
            log.info("该订单购物车信息为：{}",simpleCartVOS);
            orderCartItem.setAddress(order.getOrderAddress());
            orderCartVO.add(orderCartItem);
            DetailOrderCartVO detailOrderCartVO = new DetailOrderCartVO();
            detailOrderCartVO.setUserId(userId);
            detailOrderCartVO.setAllPrice(allPrice);
            detailOrderCartVO.setAddress(order.getOrderAddress());
            detailOrderCartVO.setCartVOS(simpleCartVOS);
            detailOrderCartVOS.add(detailOrderCartVO);
        }
        return detailOrderCartVOS;
    }

    @Override
    public List<DetailOrderCartVO> getDetailOrderByUserId() {
        log.info("根据用户查询订单列表");
        Long userId = SecurityContextUtils.getUserId();
        List<VegetableOrder> orderList = vegetableMapper.getOrderByUserId(userId);
        log.info("根据订单id查询购物车");
        List<OrderCartVO> orderCartVO = new ArrayList<>();
        List<DetailOrderCartVO> detailOrderCartVOS = new ArrayList<>();
        for (VegetableOrder order : orderList){
            Long orderId = order.getVegetableOrderId();
            List<VegetableOrderCart> orderCart = vegetableMapper.getOrderCartByOrderId(orderId);
            List<Long> cartIdList = new ArrayList<>();
            Double allPrice = 0.0;
            for (VegetableOrderCart vegetableOrderCart : orderCart){
                Long cartId = vegetableOrderCart.getVegetableCartId();
                VegetableCart cart = vegetableMapper.getCart(cartId);
                if (cart == null){
                    throw new YdtServiceException(StatusCode.BAD_REQUEST,"该购物车不存在");
                }
                Long vegetableId = cart.getVegetableId();
                Vegetable  vegetable= vegetableMapper.getVegetableById(vegetableId);
                if (vegetable == null){
                    throw new YdtServiceException(StatusCode.BAD_REQUEST,"该菜品不存在");
                }
                Double price = vegetable.getVegetablePrice();
                Integer count = cart.getCartCount();
                Double cartPrice = price*count;
                allPrice = allPrice+cartPrice;
                cartIdList.add(cartId);
            }
            OrderCartVO orderCartItem = new OrderCartVO();
            orderCartItem.setOrderId(orderId);
            orderCartItem.setAllPrice(allPrice);
            List<SimpleCartVO> simpleCartVOS = new ArrayList<>();
            for (Long cId : cartIdList){
                SimpleCartVO simpleCartVO = getCartById(cId);
                simpleCartVOS.add(simpleCartVO);
            }
            log.info("该订单购物车信息为：{}",simpleCartVOS);
            orderCartItem.setAddress(order.getOrderAddress());
            orderCartVO.add(orderCartItem);
            DetailOrderCartVO detailOrderCartVO = new DetailOrderCartVO();
            detailOrderCartVO.setUserId(userId);
            detailOrderCartVO.setAllPrice(allPrice);
            detailOrderCartVO.setAddress(order.getOrderAddress());
            detailOrderCartVO.setCartVOS(simpleCartVOS);
            detailOrderCartVOS.add(detailOrderCartVO);
        }
        return detailOrderCartVOS;

    }
}
